#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

"""One-line documentation for electricity module.

A detailed description of electricity.
"""

__author__ = 'bst@google.com (Ben Stewart)'

RIVER = 'javascript:PopupRiver'
RIVERLABELS = ['Station No','River Height (m)','Time of Observation','Flood Class','Tendency','Minor (m)','Moderate (m)','Major (m)']
RIVERELEMENTS = ['name', 'station','lat', 'long','height',
                 'floodClass','tendency', 'time','minorHeight','moderateHeight','majorHeight']

from django.utils import simplejson, html
from controllers import geocode
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import datetime
import logging
import urllib

CONFIG = {
    'vicevac': {
        'url': ('http://maps.google.com.au/maps/ms?hl=en&ie=UTF8&source=' +
                'embed&oe=UTF8&msa=0&msid=216570432711189139958.000499c1' +
                'a23499b9afcb1&output=kml'),
        'icons': [
            ('http://maps.gstatic.com/intl/en_au/mapfiles/ms/micons/' +
             'blue-dot.png',
             'http://mapvisage.appspot.com/static/floodmap/images/' +
             'rivers/evaccentre.png'),
            ('http://maps.gstatic.com/intl/en_ALL/mapfiles/ms/micons/' +
             'blue-dot.png',
             'http://mapvisage.appspot.com/static/floodmap/images/' +
             'rivers/evaccentre.png')
            ]
        },
    'vicelec': {
        'url': ('http://www.google.com/fusiontables/exporttable?query=' +
                'select+col0%2C+col1%2C+col6%2C+col7%2C+col2%2C+col5%2C+' +
                'col4%2C+col3+from+395303+&o=kmllink&g=col0'),
        'icons': [
            ('http://maps.google.com/mapfiles/kml/paddle/red-blank_maps.png',
             'http://mapvisage.appspot.com/static/floodmap/images/' +
             'power-outage.png'),
            ('<Folder id="Fusiontables">', ''),
            ('<name>Fusiontables folder</name>', ''),
            ('</Folder>', ''),
            ]
        },
    'vicses': {
        'url': ('http://www.google.com/fusiontables/exporttable?query='
                'select+col0%2C+col1%2C+col2+from+395832+&o=kmllink&g=col0'),
        'icons': [
            ('http://maps.google.com/mapfiles/kml/paddle/red-blank_maps.png',
             'http://mapvisage.appspot.com/static/floodmap/images/' +
             'caution-triangle.png'),
            ('<Folder id="Fusiontables">', ''),
            ('<name>Fusiontables folder</name>', ''),
            ('</Folder>', ''),
            ]
        },

    }

def loadMaps(mapId):
  if mapId in CONFIG:
    url = CONFIG[mapId]['url']
    icons = CONFIG[mapId]['icons']

    raw = urllib.urlopen(url)
    page = raw.read()

    for icon in icons:
      page = page.replace(icon[0], icon[1])
    return page


def updateAllMaps():
  from google.appengine.api import memcache

  for mapId in CONFIG:
    memcache.set('kmlproxy_' + mapId, loadMaps(mapId))

def updateMap(mapId):
  from google.appengine.api import memcache

  memcache.set('kmlproxy_' + mapId, loadMaps(mapId))

def showMap(mapId):
  from google.appengine.api import memcache
  kml = memcache.get('kmlproxy_' + mapId)
  if kml is None:
    updateMap(mapId)
    kml = memcache.get('kmlproxy_' + mapId)

  return kml

class UpdatePage(webapp.RequestHandler):
  def get(self):
    urlParts = self.request.path.split('/')
    mapId = ''
    if len(urlParts) >= 3:
      mapId = urlParts[2]
    updateMap(mapId)
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('OK')

class ShowPage(webapp.RequestHandler):
  def get(self):
    urlParts = self.request.path.split('/')
    mapId = ''
    if len(urlParts) >= 3:
      mapId = urlParts[2]

    self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
    now = datetime.datetime.utcnow()
    expires = now + datetime.timedelta(minutes=5)
    self.response.headers['Expires'] = (
        expires.strftime('%a, %d %b %Y %H:%M:%S GMT'))
    self.response.headers['Cache-Control'] = 'public, max_age=300'
    self.response.out.write(showMap(mapId))

class UpdateAllPage(webapp.RequestHandler):
  def get(self):
    updateAllMaps()
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('OK')

application = webapp.WSGIApplication([('/kml/update__', UpdateAllPage),
                                      ('/kml/vicevac/update__', UpdatePage),
                                      ('/kml/vicevac', ShowPage),
                                      ('/kml/vicelec/update__', UpdatePage),
                                      ('/kml/vicelec', ShowPage),
                                      ('/kml/vicses/update__', UpdatePage),
                                      ('/kml/vicses', ShowPage)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
